<?php

/**
 * sfWidgetFormJQueryCompleter
 * 
 * @package    symfext
 * @subpackage widget
 * @author     Jonathan Olger Nieto Lajo <jonathan_nieto@hotmail.com>
 */
class sfWidgetFormJQueryCompleter extends sfWidgetFormInputText
{
  protected function configure($options = array(), $attributes = array())
  {
    $this->addRequiredOption('url');
    $this->addOption('value_callback');
    $this->addOption('select_callback');
    $this->addOption('config', '{ }');
    $this->addOption('loading_image', sfConfig::get('sf_images_path').'/general/snake.gif');
    
    parent::configure($options, $attributes);
  }

  public function render($name, $value = null, $attributes = array(), $errors = array())
  {
    $visibleValue = $this->getOption('value_callback') ? call_user_func($this->getOption('value_callback'), $value) : $value;
    
    return $this->renderTag('input', array('type' => 'hidden', 'name' => $name, 'value' => $value)).
           parent::render('autocomplete_'.$name, $visibleValue, $attributes, $errors).
           $this->renderContentTag('img', null, array('src' => $this->getOption('loading_image'), 'name' => 'loading_image_'.$name, 'style' => 'display: none;')).
           $this->renderContentTag('div', null, array('name' => 'gmail_'.$name, 'class' => 'gmail_div', 'style' => $this->getOption('is_mandatory_and_unchangeable') ? 'display: none;' : '')).
           sprintf
           (
             <<<EOF
               <script type="text/javascript">
                 $(document).ready(function()
                 {
                   $("#%s").autocomplete("%s", $.extend({}, 
                   {
                     id             : "%s",   
                     dataType       : "json",
                     selectCallback : %s,
                     parse          : function(data)
                     {
                       var parsed = [];
                       for (key in data)
                       {
                         parsed[parsed.length] = { data: [ data[key], key ], value: data[key], result: data[key] };
                       }
                       
                       return parsed;
                     }
                   }, %s))
                   .result(function (event, data)
                   {
                     alert("aaa");
                   });
                 })
               </script>
EOF
             ,
             $this->generateId('autocomplete_'.$name),
             $this->getOption('url'),
             $this->generateId($name),
             $this->getOption('select_callback'),
             $this->getOption('config'),
             $this->generateId($name)
           );
  }
  
  public function getJavascripts()
  {
    return array('/js/widget/sfWidgetFormJQueryCompleter.js', '/js/widget/ListSelector.js');
  }
}
